//
//  PlayerController.swift
//  AVPlayerDemo
//
//  Created by dn56-macbook on 5/29/25.
//

import UIKit
import AVFoundation

class PlayerController: BaseViewController {
   //https://cdnq.kuso.xyz/wallpaper/wallpaper_upload/7/8f71b4daef3cdfd25f869e565c19f6f7.mp4
    let task = AVPlayerManager()
    var playerLayer : AVPlayerLayer = AVPlayerLayer()
    private var loaderDelegate: SimpleResourceLoaderDelegate?
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        guard let url = URL(string: "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4") else {
            fatalError("Wrong video url.")
        }
        
        self.loaderDelegate = SimpleResourceLoaderDelegate(withURL: url)
        let videoAsset = AVURLAsset(url: self.loaderDelegate!.streamingAssetURL)
        videoAsset.resourceLoader.setDelegate(self.loaderDelegate, queue: DispatchQueue.main)
        self.loaderDelegate?.completion = { localFileURL in
            if let localFileURL = localFileURL {
                print("Media file saved to: \(localFileURL)")
            } else {
                print("Failed to download media file.")
            }
        }

        
        // 自定义资源加载器
        let playerItem = AVPlayerItem(asset: videoAsset)
        let player = AVPlayer(playerItem: playerItem)
        self.playerLayer.player = player
        self.view.layer.addSublayer(self.playerLayer)
        self.playerLayer.videoGravity = .resizeAspect
        self.playerLayer.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.width * 1.5)
        player.play()
        
//        if let url = URL(string: "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"){
//            let player = task.startPlayback(url: url)
//            self.playerLayer.player = player
//            self.view.layer.addSublayer(self.playerLayer)
//            self.playerLayer.videoGravity = .resizeAspect
//            self.playerLayer.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.width * 1.5)
//        }
    }
    
}
